package com.fenghen.service.impl;

import com.fenghen.constans.RedisConstans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class SeckillService {

    @Autowired
    private MQProducerService mqProducerService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void seckill(Long productId) {
        // 构建Redis键，例如：product:stock:123
        String stockKey = RedisConstans.PRODUCT_STOCK + ":" + productId;

        // 预扣减库存
        Long stock = stringRedisTemplate.opsForValue().decrement(stockKey);

        if (stock != null && stock >= 0) {
            // 库存充足，发送消息队列通知数据库进行真正的库存扣减
            mqProducerService.sendStockReduceMessage(productId);
        } else {
            // 库存不足，回滚预扣减
            stringRedisTemplate.opsForValue().increment(stockKey);
            throw new RuntimeException("库存不足");
        }
    }
}
